﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using System.Windows.Forms;
using System.Data;
using Tireguit.Nmon.Parser.NmonTables;
using System.Data.Common;

namespace Tireguit.Nmon.UI.Elements.Logical
{

     public class PlotTreeElement
    {
        protected ILog _log = LogManager.GetLogger(typeof(PlotTreeElement));
        public TreeNode RootElement { get; protected set; }
        public IDbConnection Connection { get; protected set; }
        protected bool quietopened = false;
        protected DateTime _startdate = DateTime.MinValue;
        public DateTime StartDate
        {
            get { return _startdate; }
            set { _startdate = value; }
        }
        protected DateTime _enddate = DateTime.MinValue;
         public DateTime EndDate
         {
             get { return _enddate; }
             set { _enddate = value; }
         }
         protected bool QuietOpen()
         {
             try
             {
                 _log.Debug("start QuietOpen");
                 if (Connection.State == ConnectionState.Open)
                 {
                     return true;
                 }
                 Connection.Open();
                 quietopened = true;
                 return true;
             }
             catch (System.Exception ex)
             {
                 _log.Error("QuietOpen", ex);
                 return false;
             }
             finally
             {
                 _log.Debug("stop QuietOpen");
             }
         }
         protected bool QuietClose()
         {
             try
             {
                 _log.Debug("start QuietClose");
                 if (!quietopened)
                 {
                     return true;
                 }
                 if (Connection.State == ConnectionState.Closed)
                 {
                     return true;
                 }
                 Connection.Close();
                 quietopened = false;
                 return true;
             }
             catch (System.Exception ex)
             {
                 _log.Error("QuietClose", ex);
                 return false;
             }
             finally
             {
                 _log.Debug("stop QuietClose");
             }

         }
         protected bool InitLimitDateTime()
         {
             IDataReader reader = null;
             IDbCommand command = null;
             try
             {
                 _log.Debug("start InitLimitDateTime");
                 if(!QuietOpen())
                 {
                     _log.Error("Can't open database");
                     return false;
                 }
                 command = Connection.CreateCommand();
                 command.CommandText = "select min([value]) from " + TablesDictionnary.Instance["ZZZZ"];
                 reader = command.ExecuteReader();
                 if (reader.Read())
                 {
                     if (reader.IsDBNull(0))
                     {
                         _startdate = DateTime.MinValue;
                     }
                     else
                     {
                         _startdate = reader.GetDateTime(0);
                     }
                     reader.Close();
                     reader.Dispose();
                     reader = null;
                     command.CommandText = "select max([value]) from " + TablesDictionnary.Instance["ZZZZ"];
                     reader = command.ExecuteReader();
                     if (reader.Read())
                     {
                         if (reader.IsDBNull(0))
                         {
                             _enddate = DateTime.MinValue;
                         }
                         else
                         {
                             _enddate = reader.GetDateTime(0);
                         } 
                         reader.Close();
                         return true;
                     }
                 }
                 _log.Error("Fail to get Date limits");
                 return false;

             }
             catch (System.Exception ex)
             {
                 _log.Error("InitLimitDateTime", ex);
                 return false;
             }
             finally
             {
                 try
                 {
                     if (reader != null)
                     {
                         reader.Dispose();
                     }
                     if (command != null)
                     {
                         command.Dispose();
                     }
                     QuietClose();
                 }
                 catch (System.Exception)
                 {

                 }
                 _log.Debug("stop InitLimitDateTime");
             }
         }
         public  PlotTreeElement(IDbConnection connection)
         {
             Connection = connection;
             RootElement = new TreeNode("Statistiques");
             RootElement.Name = "root";
             if(!InitLimitDateTime())
             {
                 return;
             }
             TreeNode cpuelements = new TreeNode("CPUs");
             cpuelements.Name = "cpus";
             InitCpuElements(cpuelements);
             RootElement.Nodes.Add(cpuelements);
             TreeNode memelements = new TreeNode("Mémoires");
             memelements.Name = "mems";
             InitMemElements(memelements);
             RootElement.Nodes.Add(memelements);
             TreeNode diskelements = new TreeNode("Disques");
             diskelements.Name = "disks";
             InitNamedElements(diskelements, "DISKBSIZE", "S+");
             foreach (TreeNode node in diskelements.Nodes)
             {
                 InitDiskElements(node);
             }
             RootElement.Nodes.Add(diskelements);
             TreeNode jfselements = new TreeNode("Systèmes de fichiers");
             jfselements.Name = "jfss";
             TreeNode newnode = new TreeNode("JFS Files");
             newnode.Name = "S+JFSFile";
             InitNamedElements(newnode, "JFSFILE", newnode.Name+":");
             jfselements.Nodes.Add(newnode);
             newnode = new TreeNode("JFS INodes");
             newnode.Name = "S+JFSINode";
             InitNamedElements(newnode, "JFSINODE", newnode.Name+":");
             jfselements.Nodes.Add(newnode);
             RootElement.Nodes.Add(jfselements);
             TreeNode netelements = new TreeNode("Réseaux");
             netelements.Name = "nets";
             InitNetworkElements(netelements);
             RootElement.Nodes.Add(netelements);
             TreeNode adaptelements = new TreeNode("Adaptateurs");
             adaptelements.Name = "adapts";
             InitNamedElements(adaptelements, "IOADAPT", "S+IOAdapt:");
             RootElement.Nodes.Add(adaptelements);
             TreeNode filelemnts = new TreeNode("Fichiers");
             filelemnts.Name = "fils";
             InitFileElements(filelemnts);
             RootElement.Nodes.Add(filelemnts);
             TreeNode pagelements = new TreeNode("Pagination");
             pagelements.Name = "pages";
             InitPageElements(pagelements);
             RootElement.Nodes.Add(pagelements);
             TreeNode procelements = new TreeNode("Processus");
             procelements.Name = "procs";
             InitProcElements(procelements);
             RootElement.Nodes.Add(procelements);
         }
         protected void InitDiskElements(TreeNode parent)
         {
             try
             {
                 _log.Debug("start InitDiskElements");
                 TreeNode newnode = new TreeNode("DISKBSIZE");
                 newnode.Name = parent.Name + ":DISKBSIZE";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("DISKBUSY");
                 newnode.Name = parent.Name + ":DISKBUSY";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("DISKREAD");
                 newnode.Name = parent.Name + ":DISKREAD";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("DISKWRITE");
                 newnode.Name = parent.Name + ":DISKWRITE";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("DISKXFER");
                 newnode.Name = parent.Name + ":DISKXFER";
                 parent.Nodes.Add(newnode);
             }
             catch (System.Exception ex)
             {
                 _log.Error("InitDiskElements", ex);
             }
             finally
             {
                 _log.Debug("stop InitDiskElements");
             }
         }
         protected void InitCpuElements(TreeNode parent)
         {
             IDataReader reader = null;
             IDbCommand command = null;
             try
             {
                 _log.Debug("start InitCpuElements");
                 if (_startdate==DateTime.MinValue)
                 {
                     return;
                 }
                 TreeNode childnode = new TreeNode("Tous");
                 childnode.Name="S+Tous les CPU";
                 parent.Nodes.Add(childnode);
                 if (!QuietOpen())
                 {
                     _log.Error("Can't open database");
                     return ;
                 }
                 command = Connection.CreateCommand();
                 command.CommandText = "SELECT distinct c.[cpu] FROM "
                     + TablesDictionnary.Instance["CPU"] + " c INNER JOIN "
                     + TablesDictionnary.Instance["ZZZZ"] + " z "
                     + " on c.[zzzz]=z.[zzzz] WHERE z.[value] = @startdate";
                 IDbDataParameter param =command.CreateParameter();
                 param.ParameterName = "@startdate";
                 param.DbType = DbType.DateTime;
                 param.Value = _startdate;
                 command.Parameters.Add(param);
                 reader = command.ExecuteReader();
                 while(reader.Read())
                 {
                     string cpuname=reader.GetString(0);
                     childnode = new TreeNode(cpuname);
                     childnode.Name = "S+" + cpuname;
                     parent.Nodes.Add(childnode);
                 }
                 reader.Close();
                 foreach (TreeNode node in parent.Nodes)
                 {
                     TreeNode nodenew = new TreeNode("User Time%");
                     nodenew.Name = node.Name + ":User Time%";
                     node.Nodes.Add(nodenew);
                     nodenew = new TreeNode("Sys Time%");
                     nodenew.Name = node.Name + ":Sys Time%";
                     node.Nodes.Add(nodenew);
                     nodenew = new TreeNode("Wait Time%");
                     nodenew.Name = node.Name + ":Wait Time%";
                     node.Nodes.Add(nodenew);
                     nodenew = new TreeNode("Idle Time%");
                     nodenew.Name = node.Name + ":Idle Time%";
                     node.Nodes.Add(nodenew);
                 }

             }
             catch (System.Exception ex)
             {
                 _log.Error("InitCpuElements", ex);
             }
             finally
             {
                 try
                 {
                     if (reader != null)
                     {
                         reader.Dispose();
                     }
                     if (command != null)
                     {
                         command.Dispose();
                     }
                     QuietClose();
                 }
                 catch (System.Exception )
                 {
                 	
                 }
                 _log.Debug("stop InitCpuElements");
             }
         }
         protected void InitMemElements(TreeNode parent)
         {
             try
             {
                 _log.Debug("start InitMemElements");
                 if (_startdate == DateTime.MinValue)
                 {
                     return;
                 }
                 TreeNode childnode = new TreeNode("Taille");
                 childnode.Name = "S+Taille";
                 TreeNode newnode = new TreeNode("Réelle libre");
                 newnode.Name = childnode.Name + ":Realfree";
                 childnode.Nodes.Add(newnode);
                 newnode = new TreeNode("Virtuelle libre");
                 newnode.Name = childnode.Name + ":Virtualfree";
                 childnode.Nodes.Add(newnode);
                 newnode = new TreeNode("Réelle Totale");
                 newnode.Name = childnode.Name + ":Realtotal";
                 childnode.Nodes.Add(newnode);
                 newnode = new TreeNode("Virtuelle Totale");
                 newnode.Name = childnode.Name + ":Virtualtotal";
                 childnode.Nodes.Add(newnode);

                 parent.Nodes.Add(childnode);

                 childnode = new TreeNode("Utilisation");
                 childnode.Name = "S+Usage";
                 newnode = new TreeNode("Numperm%");
                 newnode.Name = childnode.Name + ":Numperm%";
                 childnode.Nodes.Add(newnode);
                 newnode = new TreeNode("Minperm%");
                 newnode.Name = childnode.Name + ":Minperm%";
                 childnode.Nodes.Add(newnode);
                 newnode = new TreeNode("Maxperm%");
                 newnode.Name = childnode.Name + ":Maxperm%";
                 childnode.Nodes.Add(newnode);
                 newnode = new TreeNode("Minfree");
                 newnode.Name = childnode.Name + ":Minfree";
                 childnode.Nodes.Add(newnode);
                 newnode = new TreeNode("Maxfree");
                 newnode.Name = childnode.Name + ":Maxfree";
                 childnode.Nodes.Add(newnode);

                 parent.Nodes.Add(childnode);
             }
             catch (System.Exception ex)
             {
                 _log.Error("InitMemElements", ex);
             }
             finally
             {
                 _log.Debug("stop InitMemElements");
             }
         }
         protected void InitNamedElements(TreeNode parent,string tablename,string radicalname)
         {
             IDataReader reader = null;
             IDbCommand command = null;
             try
             {
                 _log.Debug("start InitNamedElements");
                 if (_startdate == DateTime.MinValue)
                 {
                     return;
                 }
                 if (!QuietOpen())
                 {
                     _log.Error("Can't open database");
                     return;
                 }
                 command = Connection.CreateCommand();
                 command.CommandText = "SELECT distinct c.[name] FROM "
                     + TablesDictionnary.Instance[tablename] + " c INNER JOIN "
                     + TablesDictionnary.Instance["ZZZZ"] + " z "
                     + " on c.[zzzz]=z.[zzzz] WHERE z.[value] = @startdate"
                     +" AND c.[name]!=''";
                 IDbDataParameter param = command.CreateParameter();
                 param.ParameterName = "@startdate";
                 param.DbType = DbType.DateTime;
                 param.Value = _startdate;
                 command.Parameters.Add(param);
                 reader = command.ExecuteReader();
                 TreeNode childnode;
                 while (reader.Read())
                 {
                     string name = reader.GetString(0);
                     childnode = new TreeNode(name);
                     childnode.Name = radicalname + name;
                     parent.Nodes.Add(childnode);
                 }
                 reader.Close();
                 

             }
             catch (System.Exception ex)
             {
                 _log.Error("InitNamedElements", ex);
             }
             finally
             {
                 try
                 {
                     if (reader != null)
                     {
                         reader.Dispose();
                     }
                     if (command != null)
                     {
                         command.Dispose();
                     }
                     QuietClose();
                 }
                 catch (System.Exception)
                 {

                 }
                 _log.Debug("stop InitNamedElements");
             }
         }
         protected void InitNetworkElements(TreeNode parent)
         {
             IDataReader reader = null;
             IDbCommand command = null;
             try
             {
                 _log.Debug("start InitNetworkElements");
                 if (_startdate == DateTime.MinValue)
                 {
                     return;
                 }
                 if (!QuietOpen())
                 {
                     _log.Error("Can't open database");
                     return;
                 }
                 command = Connection.CreateCommand();
                 //net
                 command.CommandText = "SELECT distinct c.[name] FROM "
                     + TablesDictionnary.Instance["NET"] + " c INNER JOIN "
                     + TablesDictionnary.Instance["ZZZZ"] + " z "
                     + " on c.[zzzz]=z.[zzzz] WHERE z.[value] = @startdate";
                 IDbDataParameter param = command.CreateParameter();
                 param.ParameterName = "@startdate";
                 param.DbType = DbType.DateTime;
                 param.Value = _startdate;
                 command.Parameters.Add(param);
                 reader = command.ExecuteReader();
                 TreeNode netnode = new TreeNode("Adaptateur");
                 netnode.Name = "S+Adapt";
                 TreeNode childnode;
                 while (reader.Read())
                 {
                     string name = reader.GetString(0);
                     childnode = new TreeNode(name);
                     childnode.Name = netnode.Name+":" + name;
                     netnode.Nodes.Add(childnode);
                 }
                 reader.Close();
                 parent.Nodes.Add(netnode);
                 //netpacket
                 command.CommandText = "SELECT distinct c.[name] FROM "
                     + TablesDictionnary.Instance["NETPACKET"] + " c INNER JOIN "
                     + TablesDictionnary.Instance["ZZZZ"] + " z "
                     + " on c.[zzzz]=z.[zzzz] WHERE z.[value] = @startdate";
                 param = command.CreateParameter();
                 param.ParameterName = "@startdate";
                 param.DbType = DbType.DateTime;
                 param.Value = _startdate;
                 command.Parameters.Clear();
                 command.Parameters.Add(param);
                 reader = command.ExecuteReader();
                 netnode = new TreeNode("Paquets");
                 netnode.Name = "S+Packet";
                 while (reader.Read())
                 {
                     string name = reader.GetString(0);
                     childnode = new TreeNode(name);
                     childnode.Name = netnode.Name + ":" + name;
                     netnode.Nodes.Add(childnode);
                 }
                 reader.Close();
                 parent.Nodes.Add(netnode);
                 //neterror
                 command.CommandText = "SELECT distinct c.[name] FROM "
                     + TablesDictionnary.Instance["NETERROR"] + " c INNER JOIN "
                     + TablesDictionnary.Instance["ZZZZ"] + " z "
                     + " on c.[zzzz]=z.[zzzz] WHERE z.[value] = @startdate";
                 param = command.CreateParameter();
                 param.ParameterName = "@startdate";
                 param.DbType = DbType.DateTime;
                 param.Value = _startdate;
                 command.Parameters.Clear();
                 command.Parameters.Add(param);
                 reader = command.ExecuteReader();
                 netnode = new TreeNode("Erreurs");
                 netnode.Name = "S+NetError";
                 while (reader.Read())
                 {
                     string name = reader.GetString(0);
                     childnode = new TreeNode(name);
                     childnode.Name = netnode.Name + ":" + name;
                     netnode.Nodes.Add(childnode);
                 }
                 reader.Close();
                 parent.Nodes.Add(netnode);



             }
             catch (System.Exception ex)
             {
                 _log.Error("InitNetworkElements", ex);
             }
             finally
             {
                 try
                 {
                     if (reader != null)
                     {
                         reader.Dispose();
                     }
                     if (command != null)
                     {
                         command.Dispose();
                     }
                     QuietClose();
                 }
                 catch (System.Exception)
                 {

                 }
                 _log.Debug("stop InitNetworkElements");
             }
         }
         protected void InitPageElements(TreeNode parent)
         {
             try
             {
                 _log.Debug("start InitPageElements");
                 if (_startdate == DateTime.MinValue)
                 {
                     return;
                 }
                 string name = "S+Page";
                 TreeNode newnode = new TreeNode("faults");
                 newnode.Name = name + ":faults";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("pgin");
                 newnode.Name = name + ":pgin";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("pgout");
                 newnode.Name = name + ":pgout";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("pgsin");
                 newnode.Name = name + ":pgsin";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("pgsout");
                 newnode.Name = name + ":pgsout";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("reclaims");
                 newnode.Name = name + ":reclaims";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("scans");
                 newnode.Name = name + ":scans";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("cycles");
                 newnode.Name = name + ":cycles";
                 parent.Nodes.Add(newnode);
                 
             }
             catch (System.Exception ex)
             {
                 _log.Error("InitPageElements", ex);
             }
             finally
             {
                 _log.Debug("stop InitPageElements");
             }
         }
         protected void InitProcElements(TreeNode parent)
         {
             try
             {
                 _log.Debug("start InitProcElements");
                 if (_startdate == DateTime.MinValue)
                 {
                     return;
                 }
                 string name = "S+Proc";
                 TreeNode newnode = new TreeNode("Runnable");
                 newnode.Name = name + ":Runnable";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("Swapin");
                 newnode.Name = name + ":Swapin";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("pswitch");
                 newnode.Name = name + ":pswitch";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("syscall");
                 newnode.Name = name + ":syscall";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("read");
                 newnode.Name = name + ":read";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("write");
                 newnode.Name = name + ":write";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("fork");
                 newnode.Name = name + ":fork";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("exec");
                 newnode.Name = name + ":exec";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("rcvint");
                 newnode.Name = name + ":rcvint";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("xmtint");
                 newnode.Name = name + ":xmtint";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("sem");
                 newnode.Name = name + ":sem";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("msg");
                 newnode.Name = name + ":msg";
                 parent.Nodes.Add(newnode);

             }
             catch (System.Exception ex)
             {
                 _log.Error("InitProcElements", ex);
             }
             finally
             {
                 _log.Debug("stop InitProcElements");
             }
         }
         protected void InitFileElements(TreeNode parent)
         {
             try
             {
                 _log.Debug("start InitFileElements");
                 if (_startdate == DateTime.MinValue)
                 {
                     return;
                 }
                 string name = "S+File";
                 TreeNode newnode = new TreeNode("iget");
                 newnode.Name = name + ":iget";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("namei");
                 newnode.Name = name + ":namei";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("dirblk");
                 newnode.Name = name + ":dirblk";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("readch");
                 newnode.Name = name + ":readch";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("writech");
                 newnode.Name = name + ":writech";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("ttyrawch");
                 newnode.Name = name + ":ttyrawch";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("ttycanch");
                 newnode.Name = name + ":ttycanch";
                 parent.Nodes.Add(newnode);
                 newnode = new TreeNode("ttyoutch");
                 newnode.Name = name + ":ttyoutch";
                 parent.Nodes.Add(newnode);
                 
             }
             catch (System.Exception ex)
             {
                 _log.Error("InitFileElements", ex);
             }
             finally
             {
                 _log.Debug("stop InitFileElements");
             }
         }
     }
}
